<template>
  <div class="dictionary-management-page">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" ref="searchForm">
        <el-form-item label="字典名称">
          <el-input
            v-model="searchForm.dictName"
            placeholder="请输入字典名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编号">
          <el-input
            v-model="searchForm.dictCode"
            placeholder="请输入字典编号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="btn-group">
        <el-button type="success" @click="handleAdd">添加</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
    >
      <el-table-column prop="dictName" label="字典名称" width="100"></el-table-column>
      <el-table-column prop="dictCode" label="字典编码" width="100"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="150"></el-table-column>
      <el-table-column prop="updatedTime" label="更新时间" width="150"></el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDictConfig(scope.row)">字典配置</el-button>
          <el-button
            type="text"
            :style="{ color: 'red' }"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog 
      :title="editForm.id ? '编辑字典' : '添加字典'" 
      :visible.sync="editDialogVisible" 
      width="50%"
    >
      <el-form 
        ref="editForm" 
        :model="editForm" 
        :rules="editFormRules" 
        label-width="120px"
      >
        <el-form-item label="字典名称" prop="dictName">
          <el-input 
            v-model="editForm.dictName" 
            placeholder="请输入字典名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编码" prop="dictCode">
          <el-input 
            v-model="editForm.dictCode" 
            placeholder="请输入字典编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            placeholder="请输入描述" 
            type="textarea" 
            rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增：子字典配置弹窗 -->
<el-dialog 
  :title="`字典配置 - ${currentMainDictName}`" 
  :visible.sync="dictConfigVisible" 
  width="60%"
>
  <!-- 子字典搜索 -->
  <div style="margin-bottom: 15px;">
    <el-input 
      v-model="subSearchForm.itemCh" 
      placeholder="搜索子字典名称" 
      clearable 
      style="width: 240px; margin-right: 10px;"
      @keyup.enter="fetchSubTableData"
    />
     <!-- 新增：字典编号搜索框 -->
  <el-input 
    v-model="subSearchForm.itemValue" 
    placeholder="搜索子字典编号" 
    clearable 
    style="width: 240px; margin-right: 10px;"
    @keyup.enter="fetchSubTableData"
  />
    <el-button type="primary" @click="fetchSubTableData">搜索</el-button>
    <el-button type="primary" @click="handleSubAdd">添加</el-button>
  </div>

  <!-- 子字典表格 -->
  <el-table
    :data="subTableData"
    stripe
    v-loading="subTableLoading"
    element-loading-text="正在加载子字典数据..."
    style="margin-bottom: 10px;"
  >
    <el-table-column prop="itemCh" label="子字典名称" width="120"></el-table-column>
    <el-table-column prop="itemValue" label="子字典值" width="120"></el-table-column>
    <el-table-column prop="description" label="描述"></el-table-column>
    <el-table-column prop="createdTime" label="创建时间" width="160"></el-table-column>
    <el-table-column label="操作" width="220">
      <template #default="scope">
        <el-button type="text" @click="handleSubEdit(scope.row)">编辑</el-button>
        <el-button 
          type="text" 
          :style="{ color: 'red' }" 
          @click="handleSubDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 子字典分页 -->
  <el-pagination
    @size-change="handleSubSizeChange"
    @current-change="handleSubCurrentChange"
    :current-page="subCurrentPage"
    :page-sizes="[5, 10, 20]"
    :page-size="subPageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="subTotalCount"
    style="text-align: right;"
  ></el-pagination>

  <!-- 子字典编辑/新增弹窗 -->
  <el-dialog 
    :title="subEditForm.id ? '编辑子字典' : '添加子字典'" 
    :visible.sync="subEditDialogVisible" 
    width="50%"
     append-to-body 
    modal-append-to-body  
  >
    <el-form 
      ref="subEditForm" 
      :model="subEditForm" 
      :rules="subEditFormRules" 
      label-width="200px"
    >
     <!-- 新增：父字典Code字段（只读） -->
          <el-form-item label="父字典编码" prop="dictCode">
            <el-input 
              v-model="subEditForm.dictCode" 
              placeholder="父字典编码"
              :readonly="true"  
              :disabled="true"  
              style="background-color: #f5f7fa;" 
            ></el-input>
          </el-form-item>
      <el-form-item label="子字典名称" prop="itemCh">
        <el-input 
          v-model="subEditForm.itemCh" 
          placeholder="请输入子字典名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="子字典值" prop="itemValue">
        <el-input 
          v-model="subEditForm.itemValue" 
          placeholder="请输入子字典值"
        ></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="subEditForm.description" 
          placeholder="请输入描述" 
          type="textarea" 
          rows="4"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="subEditDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitSubEditForm">确定</el-button>
    </div>
  </el-dialog>
</el-dialog>
  </div>
</template>
<script>
export default {
  name: "DictionaryManagement",
  data() {
    return {
        
    // 子字典搜索表单（扩展 itemValue）
    subSearchForm: { 
      itemCh: "",   // 子字典名称
      itemValue: "" // 子字典编号（新增）
    },  
    
      // 搜索表单
       // 新增：子字典配置相关
    dictConfigVisible: false,        // 子字典配置弹窗显隐
    currentMainDictId: null,         // 当前主字典ID
    currentMainDictName: "",         // 当前主字典名称
    subTableData: [],                // 子字典表格数据
    subTableLoading: false,          // 子字典加载状态
    subTotalCount: 0,                // 子字典总条数
    subCurrentPage: 1,               // 子字典当前页
    subPageSize: 5,                  // 子字典每页条数
    subEditDialogVisible: false,     // 子字典编辑弹窗显隐
    subEditForm: {                   // 子字典编辑表单
      id: null,
      itemCh: "",
      itemValue: "",
      description: "",
      dictCode: "",  // 关联主字典的dictCode
    },
    subEditFormRules: {              // 子字典校验规则
      itemCh: [
        { required: true, message: "请输入子字典名称", trigger: "blur" },
        { min: 1, max: 50, message: "长度在 1-50 字符", trigger: "blur" }
      ],
      itemValue: [
        { required: true, message: "请输入子字典值", trigger: "blur" },
        { min: 1, max: 32, message: "长度在 1-32 字符", trigger: "blur" }
      ]
    },
      searchForm: {
        dictName: "",
        dictCode: "",
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      // 编辑/新增弹窗相关
      editDialogVisible: false,
      editForm: {
        id: null,
        dictName: "",
        dictCode: "",
        description: "",
      },
      // 表单验证规则
      editFormRules: {
        dictName: [
          { required: true, message: "请输入字典类型", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
        ],
        dictCode: [
          { required: true, message: "请输入字典编码", trigger: "blur" },
          { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
        ],
        description: [
          { required: false, message: "请输入描述", trigger: "blur" },
          { min: 0, max: 200, message: "长度在 0 到 200 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.fetchTableData();
  },
  methods: {
    // 新增：子字典方法
  // 打开子字典配置弹窗
  handleDictConfig(row) {
    this.currentMainDictId = row.dictCode;
    this.currentMainDictName = row.dictName;
    this.dictConfigVisible = true;
    this.subSearchForm.itemCh = "";
    this.subCurrentPage = 1;
    this.fetchSubTableData(); // 加载子字典数据
  },

  // 获取子字典表格数据
  async fetchSubTableData() {
    this.subTableLoading = true;
    try {
      const res = await this.$request.post(
        "/system/sysDict/searchItem", // 子字典查询接口
        {
          currentPage: this.subCurrentPage,
          pageSize: this.subPageSize,
          dictCode: this.currentMainDictId, // 关联主字典ID
          itemCh: this.subSearchForm.itemCh, // 子字典名称搜索
                  itemValue: this.subSearchForm.itemValue // 编号搜索（新增）

        }
      );
      if (res.code === 200) {
        this.subTableData = res.data.records;
        this.subTotalCount = Number(res.data.total);
      }
    } catch (error) {
      console.error("获取子字典数据失败:", error);
      this.$message.error("网络错误，请重试");
    } finally {
      this.subTableLoading = false;
    }
  },

  // 添加子字典
  handleSubAdd() {
    this.subEditForm = {
      id: null,
      itemCh: "",
      itemValue: "",
      description: "",
      dictCode: this.currentMainDictId // 关联主字典
    };
    this.subEditDialogVisible = true;
  },

  // 编辑子字典
  handleSubEdit(row) {
    this.subEditForm = {
      id: row.id,
      itemCh: row.itemCh,
      itemValue: row.itemValue,
      description: row.description || "",
      dictCode: this.currentMainDictId
    };
    this.subEditDialogVisible = true;
  },

  // 提交子字典编辑表单
  async submitSubEditForm() {
    this.$refs.subEditForm.validate(async (valid) => {
      if (valid) {
        try {
          let res;
          if (this.subEditForm.id) {
            res = await this.$request.post("/system/sysDict/updateItem", this.subEditForm);
          } else {
            res = await this.$request.post("/system/sysDict/addItem", this.subEditForm);
          }
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.subEditDialogVisible = false;
            this.fetchSubTableData(); // 刷新子字典列表
          } else {
            this.$message.error("操作失败：" + (res.msg || "未知错误"));
          }
        } catch (error) {
          console.error("操作失败:", error);
          this.$message.error("网络错误，请重试");
        }
      }
    });
  },

  // 删除子字典
  

  // 子字典分页-每页条数变化
  handleSubSizeChange(val) {
    this.subPageSize = val;
    this.fetchSubTableData();
  },

  // 子字典分页-当前页变化
  handleSubCurrentChange(val) {
    this.subCurrentPage = val;
    this.fetchSubTableData();
  },
    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        const res = await this.$request.post(
          "/system/sysDict/search", 
          {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            ...this.searchForm,
          }
        );
        if (res.code === 200) {
          console.log("dada",res)
          this.tableData = res.data.records;
          this.totalCount = Number(res.data.total);
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.tableLoading = false;
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },
    // 添加字典
    handleAdd() {
       this.$nextTick(() => {
    this.$refs.editForm && this.$refs.editForm.resetFields();
  });
      this.editForm = {
        id: null,
        dictName: "",
        dictCode: "",
        description: "",
      };
      this.editDialogVisible = true;
    },
    // 编辑操作 - 打开弹窗并回显数据
    handleEdit(row) {
       this.$nextTick(() => {
    this.$refs.editForm && this.$refs.editForm.resetFields();
  });
      this.editForm = {
        id: row.id,
        dictName: row.dictName,
        dictCode: row.dictCode,
        description: row.description || "",
      };
      this.editDialogVisible = true;
    },
    // 关闭弹窗
    handleDialogClose() {
      this.editDialogVisible = false;
      this.$refs.editForm && this.$refs.editForm.resetFields();
    },
    // 提交编辑/新增表单
    async submitEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.editForm.id) {
              // 编辑操作，调用更新接口
              res = await this.$request.post(
                "/system/sysDict/update", 
                this.editForm
              );
            } else {
              // 新增操作，调用新增接口
              res = await this.$request.post(
                "/system/sysDict/add", 
                this.editForm
              );
            }
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.editDialogVisible = false;
              this.fetchTableData();
            } else {
              this.$message.error("操作失败：" + (res.msg || "未知错误"));
            }
          } catch (error) {
            console.error("操作失败:", error);
            this.$message.error("网络错误，请重试");
          }
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    // 删除操作
   // 主字典删除方法（按示例修改）
async handleDelete(row) {
  // 获取当前点击的删除按钮元素
  const button = document.activeElement;

  this.$confirm(
    `确定要删除字典【${row.dictName}】吗？删除后不可恢复`,
    "提示",
    { type: "error" }
  )
    .then(async () => {
      try {
        const res = await this.$request.post("/system/sysDict/delete", { id: row.id });
        if (res.code === 200) {
          this.$message.success("删除成功");
          this.fetchTableData();
        } else {
          this.$message.error(`删除失败: ${res.msg || "未知错误"}`);
        }
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error("删除失败，请重试");
      }
    })
    .catch(() => {
      this.$message.info("已取消删除");
    })
    .finally(() => {
      // 延迟执行失焦处理，确保按钮状态重置
      if (button && typeof button.blur === 'function') {
        setTimeout(() => {
          button.blur(); // 按钮失焦
          document.body.focus(); // 焦点移至body
        }, 100);
      }
    });
},

// 子字典删除方法（同步修改）
async handleSubDelete(row) {
  // 获取当前点击的删除按钮元素
  const button = document.activeElement;

  this.$confirm(
    `确定要删除子字典【${row.itemCh}】吗？删除后不可恢复`,
    "提示",
    { type: "error" }
  )
    .then(async () => {
      try {
        const res = await this.$request.post("/system/sysDict/deleteItem", { id: row.id });
        if (res.code === 200) {
          this.$message.success("删除成功");
          this.fetchSubTableData();
        } else {
          this.$message.error(`删除失败: ${res.msg || "未知错误"}`);
        }
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error("删除失败，请重试");
      }
    })
    .catch(() => {
      this.$message.info("已取消删除");
    })
    .finally(() => {
      // 延迟执行失焦处理，确保按钮状态重置
      if (button && typeof button.blur === 'function') {
        setTimeout(() => {
          button.blur(); // 按钮失焦
          document.body.focus(); // 焦点移至body
        }, 100);
      }
    });
},
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },
  },
};
</script><style scoped>
.dictionary-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.btn-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table td,
::v-deep .el-table th {
  text-align: center;
}

/* 响应式 */
@media screen and (max-width: 1200px) {
  .search-section {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>